import 'package:flutter/services.dart';
import 'package:manual/utils/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:intl/intl.dart'; 


class DownloadImage {
  static getTimeimg (){
    final now = DateTime.now();
    final formattedDate = DateFormat('yyyy_MM_dd_HHmmssSSS').format(now);
    return formattedDate;
  } 


  // 保存网络图片到本地文件
  static Future<String?> downloadImage(String url) async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final tempDir = await getTemporaryDirectory();
        final filePath = '${tempDir.path}/${getTimeimg()}_image.jpg';

        final file = File(filePath);
        await file.writeAsBytes(response.bodyBytes);
        return file.path; // 返回本地路径
      } else {
        Logger.warn(' 下载失败$response.statusCode', tag: 'downloadImage');
        return null;
      }
    } catch (e) {
      Logger.warn('方法执行失败$e', tag: 'downloadImage');
      return null;
    }
  }

  // 保存项目文件 lib下的 到手机文件
  static Future<String?> copyAssetToFilePath(String assetPath) async {
    try {
      // 获取缓存目录
      final tempDir = await getTemporaryDirectory();
      final filePath = '${tempDir.path}/${getTimeimg()}_.png';

      // 读取 asset 数据并写入文件
      final byteData = await rootBundle.load(assetPath);
      final buffer = byteData.buffer;
      final file = File(filePath);
      await file.writeAsBytes(
          buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

      return file.path; // 返回文件路径
    } catch (e) {
      Logger.error("保存临时图片失败 $e", tag: "copyAssetToFilePath");
      return null;
    }
  }
}
